package cn.basic.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class AsynclFutureService {
    protected static Logger logger = LoggerFactory.getLogger(AsynclFutureService.class);

    @Async
    public Future<Long> test() {
        Long n=test1();
        return new AsyncResult<Long>(n);
    }

    public Long test1() {
        ExecutorService es = Executors.newFixedThreadPool(10);
        AtomicLong totalAll = new AtomicLong(0);
        CountDownLatch cdl = new CountDownLatch(20);
        AtomicLong partId = new AtomicLong(0);

        for (int i = 0; i < 20; i++) {
            es.execute(new Runnable() {
                @Override
                public void run() {
                    totalAll.getAndAdd(processUserData(partId.getAndIncrement()));
                    cdl.countDown();
                }
            });
        }
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return totalAll.get();

    }
    public Long processUserData(Long partid){

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 20; i++) {
            if(partid==i){
                Long n=Long.valueOf(i)+1;
                System.out.println("分区 "+partid+" 完成"+n);
                return n;
            }
        }
        return 0L;
    }

}